package com.leibun.gpstoggle;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.location.LocationManager;
import android.provider.Settings;

public class GpsToggleUtil {
	/**
	 * Gets the state of GPS location.
	 * @param context
	 * @return true if enabled.
	 */

	public static boolean getGpsState(Context context) {

		ContentResolver resolver = context.getContentResolver();

		return Settings.Secure.isLocationProviderEnabled(resolver,
				LocationManager.GPS_PROVIDER);

	}

	/**
	 * Toggles the state of GPS.
	 * @param context
	 */
	public static void toggleGps(Context context) {
		ContentResolver resolver = context.getContentResolver();

		boolean enabled = getGpsState(context);

		Settings.Secure.setLocationProviderEnabled(resolver,LocationManager.GPS_PROVIDER,!enabled);

	}
	
	/**
	 * Notifies the GPS state in the status bar.
	 * @param context
	 */
	public static void notifyGpsState(Context context){
		Resources res =  context.getResources();
		
		String gps_state;
		int drawableID;

		if(GpsToggleUtil.getGpsState(context)){
			gps_state = res.getString(R.string.gps_on);
			drawableID = R.drawable.stat_sys_gps_on;
		}else{
			gps_state = res.getString(R.string.gps_off);
			drawableID = R.drawable.stat_sys_gps_acquiring;
		}

		String message = res.getString(R.string.notification_message);
		String contentTitle = res.getString(R.string.app_name);
		
		NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(
				drawableID, message, System.currentTimeMillis());
		Intent intent = new Intent(context,GpsToggleService.class);
		PendingIntent contentIntent = PendingIntent.getService(context, 0,intent, 0);
		notification.setLatestEventInfo(context, contentTitle ,gps_state, contentIntent);
		notification.flags = Notification.FLAG_ONGOING_EVENT;
		notificationManager.notify(R.string.app_name, notification);
	}
}
